package com.lj.sys.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.lj.common.utils.RedisUtil;
import com.lj.mp.standard.StandardServiceImpl;
import com.lj.mp.utils.PageQueryUtils;
import com.lj.sys.entity.SysConfig;
import com.lj.sys.mapper.SysConfigMapper;
import com.lj.sys.param.SysConfigPageParam;
import com.lj.sys.param.SysConfigSaveParam;
import com.lj.sys.param.SysConfigUpdateParam;
import com.lj.sys.result.SysConfigInfoResult;
import com.lj.sys.result.SysConfigPageResult;
import com.lj.sys.service.SysConfigService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

/**
 * <p>
 * 系统配置表 服务实现类
 * </p>
 *
 * @author luojing
 * @since 2025-02-21 14:11:02
 */
@Service
public class SysConfigServiceImpl extends StandardServiceImpl<SysConfigMapper, SysConfig> implements SysConfigService {

    private static final String SYS_CONFIG_KEY = "sys_config:";
    @Resource
    private RedisUtil redisUtil;

    @Override
    public IPage<SysConfigPageResult> page(SysConfigPageParam param) {
        return this.page(PageQueryUtils.getPage(param), getQueryWrapper(param)).convert(SysConfigPageResult::of);
    }

    private LambdaQueryWrapper<SysConfig> getQueryWrapper(SysConfigPageParam param) {
        return lambdaQueryWrapper()
                .eq(ObjectUtil.isNotEmpty(param.getConfigKey()), SysConfig::getConfigKey, param.getConfigKey())
                .eq(ObjectUtil.isNotEmpty(param.getCategory()), SysConfig::getCategory, param.getCategory())
                ;
    }

    @Override
    public SysConfigInfoResult info(Long id) {
        return SysConfigInfoResult.of(this.getById(id));
    }

    @Override
    public void save(SysConfigSaveParam param) {
        SysConfig entity = param.toEntity();
        this.save(entity);
    }

    @Override
    public void update(SysConfigUpdateParam param) {
        SysConfig entity = param.toEntity();
        this.updateById(entity);
        // 移除缓存
        deleteCache(Collections.singletonList(entity.getId()));
    }

    @Override
    public void delete(List<Long> ids) {
        if (CollUtil.isEmpty(ids)) {
            return;
        }
        // 先删缓存再删库
        deleteCache(ids);
        this.removeByIds(ids);
    }

    private void deleteCache(List<Long> ids) {
        if (CollUtil.isEmpty(ids)) {
            return;
        }
        List<String> deleteCacheKey = listByIds(ids).stream().map(sysConfig -> SYS_CONFIG_KEY + sysConfig.getConfigKey()).toList();
        redisUtil.delete(deleteCacheKey);
    }

    @Override
    public String getValue(String configKey) {
        String cacheValue = redisUtil.get(SYS_CONFIG_KEY + configKey);
        if (cacheValue != null) {
            // 之前查询过 哪怕是空字符串
            return cacheValue;
        }
        SysConfig sysConfig = this.getOne(lambdaQueryWrapper()
                .select(SysConfig::getConfigValue)
                .eq(SysConfig::getConfigKey, configKey)
                .last("limit 1"));
        if (sysConfig == null) {
            return null;
        }
        // 缓存
        redisUtil.set(SYS_CONFIG_KEY + configKey, sysConfig.getConfigValue());
        return sysConfig.getConfigValue();
    }


    @Override
    public Integer getIntegerValue(String configKey) {
        String value = getValue(configKey);
        if (StrUtil.isBlank(value)) {
            return null;
        }
        return NumberUtil.parseInt(value);
    }

    @Override
    public Boolean getBooleanValue(String configKey) {
        String value = getValue(configKey);
        if (StrUtil.isBlank(value)) {
            return null;
        }
        return BooleanUtil.toBooleanObject(value);
    }

    @Override
    public <T> T getJsonValue(String configKey, Class<T> valueClass) {
        String value = getValue(configKey);
        if (StrUtil.isBlank(value)) {
            return null;
        }
        return JSONUtil.toBean(value, valueClass);
    }
}
